---
interface Props {
  mapping: string;
}

const { mapping } = Astro.props;
---

<div class="giscus"></div>

<script is:inline>
  function loadGiscus() {
    const script = document.createElement('script');
    script.src = 'https://giscus.app/client.js';
    script.setAttribute('data-repo', 'chovYena/uni-vite-preset');
    script.setAttribute('data-repo-id', 'R_kgDOKMV_qg');
    script.setAttribute('data-category', 'Q&A');
    script.setAttribute('data-category-id', 'DIC_kwDOKMV_qs4CkUrb');
    script.setAttribute('data-mapping', 'pathname');
    script.setAttribute('data-strict', '0');
    script.setAttribute('data-reactions-enabled', '1');
    script.setAttribute('data-emit-metadata', '0');
    script.setAttribute('data-input-position', 'top');
    script.setAttribute('data-theme', document.documentElement.classList.contains('dark') ? 'dark' : 'light');
    script.setAttribute('data-lang', 'zh-CN');
    script.setAttribute('data-loading', 'lazy');
    script.crossOrigin = 'anonymous';
    script.async = true;

    const container = document.querySelector('.giscus');
    if (container) {
      container.innerHTML = '';
      container.appendChild(script);
    }
  }

  // 初始加载
  loadGiscus();

  // 监听主题变化
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.attributeName === 'class') {
        const isDark = document.documentElement.classList.contains('dark');
        const iframe = document.querySelector('iframe.giscus-frame');
        if (iframe) {
          iframe.contentWindow.postMessage(
            { giscus: { setConfig: { theme: isDark ? 'dark' : 'light' } } },
            'https://giscus.app'
          );
        } else {
          loadGiscus();
        }
      }
    });
  });

  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['class']
  });
</script>

<style>
  .giscus {
    width: 100%;
    margin-top: 2rem;
  }

  /* 暗色模式适配 */
  :global(.dark) .giscus-frame {
    background-color: transparent;
  }
</style> 